package com.keyinong.parkin.customdatapicker;

import java.text.DecimalFormat;
import java.util.ArrayList;
import com.keyinong.parkin.util.MyToast;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

/**
 * 自定义日历卡
 * 
 * @author wuwenjie
 * 
 */
public class CalendarCardNotice extends View {
	/** 7列 */
	private static final int TOTAL_COL = 7;
	/** 6行 */
	private static final int TOTAL_ROW = 6;

	/** 绘制圆形的画笔 */
	private Paint mCirclePaint;
	private Paint mOnclickPaint;// 绘制点击的圆形画笔
	/** 绘制文本的画笔 */
	private Paint mTextPaint;
	/** 绘制选择文本的画笔 */
	private Paint mTextOnc;
	/** 视图的宽度 */
	private int mViewWidth;
	/** 视图的高度 */
	private int mViewHeight;
	/** 单元格间距 */
	private int mCellSpace;
	/** 行数组，每个元素代表一行 */
	private Row rows[] = new Row[TOTAL_ROW];
	/** 自定义的日期，包括year,month,day */
	private static CustomDate mShowDate;
	/** 单元格点击回调事件 */
	private OnCellClickListener mCellClickListener;
	private int touchSlop; //
	private boolean callBackCellSpace;

	private Cell mClickCell;
	/** 按下的位置的x */
	private float mDownX;
	/** 按下的位置的y */
	private float mDownY;

	private int wx, hy;
	private Canvas canvasSelect;

	private Context context;

	private ArrayList<String> canselectlist;

	private int changeMonth;

	DecimalFormat df = new DecimalFormat("00");
	private ArrayList<String> selectetlist = new ArrayList<String>();

	/**
	 * 单元格点击的回调接口
	 * 
	 * @author wuwenjie
	 * 
	 */
	public interface OnCellClickListener {
		void clickDate(CustomDate date); // 回调点击的日期
		// void onMesureCellHeight(int cellSpace);//回调cell的高度确定slidingDrawer高度

//		void changeDate(CustomDate date); // 回调滑动ViewPager改变的日期
	}

//	public void setOnCellClickListener(OnCellClickListener oncell) {
//		mCellClickListener = oncell;
//		// canvasSelect=new Canvas();
//		// void clickDate(CustomDate date);
//	}

	public CalendarCardNotice(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		this.context = context;
//		init(context);
	}

	public CalendarCardNotice(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
//		init(context);
	}

	public CalendarCardNotice(Context context) {
		super(context);
		this.context = context;
//		init(context);
	}

	public void getwh() {

	}

	public CalendarCardNotice(Context context, OnCellClickListener listener,
			ArrayList<String> list, int changeMonth) {
		super(context);
		this.context = context;
		this.mCellClickListener = listener;
		this.canselectlist = list;
		this.changeMonth = changeMonth;
		init(context);
		// selectDate(context);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// canvasSelect=canvas;
		for (int i = 0; i < TOTAL_ROW; i++) {
			if (rows[i] != null) {
				rows[i].drawCells(canvas);
			}
		}
		// selectDate(canvas);
	}

	/** 画白色的圆形 */
	private void init(Context context) {
		mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mCirclePaint.setStyle(Paint.Style.FILL);
		mCirclePaint.setColor(Color.parseColor("#00b4ff")); // 白色圆形
		// mCirclePaint.setColor(getResources().getColor(R.color.white));
		touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
		selectDate();
		initDate();
	}

	private void selectDate() {
		mTextOnc = new Paint(Paint.ANTI_ALIAS_FLAG);
		mOnclickPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mOnclickPaint.setStyle(Paint.Style.FILL);
		mOnclickPaint.setColor(Color.parseColor("#1ef16e")); // 黄色
		touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		mViewWidth = w;
		mViewHeight = 310;
		// 数组取最大
		mCellSpace = Math.max(mViewHeight / TOTAL_ROW, mViewWidth / TOTAL_COL);
		// mCellSpace = Math.min(mViewHeight / TOTAL_ROW, mViewWidth /
		// TOTAL_COL);
		if (!callBackCellSpace) {
			// mCellClickListener.onMesureCellHeight(mCellSpace);
			callBackCellSpace = true;
		}
		// Log.e("lh", "mViewWidth--"+mViewWidth);
		// Log.e("lh", "mViewHeight--"+mViewHeight);
		// Log.e("lh", "w--"+w);
		// Log.e("lh", "h--"+h);
		// Log.e("lh", "oldw--"+oldw);
		// Log.e("lh", "oldh--"+oldh);
		// Log.e("lh", "mCellSpace--"+mCellSpace);
		// Log.e("lh", "mCellSpace / 3--"+mCellSpace / 3);
		mTextPaint.setTextSize(mCellSpace / 3);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mDownX = event.getX();
			mDownY = event.getY();
			break;
		case MotionEvent.ACTION_UP:
			float disX = event.getX() - mDownX;
			float disY = event.getY() - mDownY;
			if (Math.abs(disX) < touchSlop && Math.abs(disY) < touchSlop) {
				int col = (int) (mDownX / mCellSpace);
				int row = (int) (mDownY / mCellSpace);
				measureClickCell(col, row);

			}
			break;
		default:
			break;
		}

		return true;
	}

	/**
	 * 计算点击的单元格
	 * 
	 * @param col
	 * @param row
	 */
	private void measureClickCell(int col, int row) {
		if (col >= TOTAL_COL || row >= TOTAL_ROW)
			return;
		if (mClickCell != null) {
			rows[mClickCell.j].cells[mClickCell.i] = mClickCell;
		}
		if (rows[row] != null) {
			mClickCell = new Cell(rows[row].cells[col].date,
					rows[row].cells[col].state, rows[row].cells[col].i,
					rows[row].cells[col].j);

			CustomDate date = rows[row].cells[col].date;
			date.week = col;

			// 判断点击的时间区域
			String selectMonth = date.getMonth() < 10 ? "0" + date.getMonth()
					: "" + date.getMonth();
			String selectDay = date.getDay() < 10 ? "0" + date.getDay() : ""
					+ date.getDay();

			String curMonth = DateUtil.getMonth() < 10 ? "0"
					+ DateUtil.getMonth() : DateUtil.getMonth() + "";
			String curDay = DateUtil.getCurrentMonthDay() < 10 ? "0"
					+ DateUtil.getCurrentMonthDay() : DateUtil
					.getCurrentMonthDay() + "";

			int curDate = Integer.parseInt("" + DateUtil.getYear() + curMonth
					+ curDay);
			int ClickDate = Integer.parseInt("" + date.getYear() + selectMonth
					+ selectDay);
			// Log.e("lh", "ClickDate=" + ClickDate + "curDate=" + curDate +
			// "--"
			// + (ClickDate - curDate));
			if (ClickDate - curDate < 0) {
				MyToast.mToast(context, "不能选择过去的日期");
				return;
			}

			// 小于一年
			int jsyeat = Math.abs(date.getYear() - DateUtil.getYear());
			if (jsyeat > 1) {
				MyToast.mToast(context, "不能选择超过三十天的日期");
				return;
			}
			if (jsyeat == 1) {
				if (Math.abs(date.getMonth() - DateUtil.getMonth()) != 11) {
					MyToast.mToast(context, "不能选择超过三十天的日期");
					return;
				}
			} else if (Math.abs(date.getMonth() - DateUtil.getMonth()) > 2) {
				MyToast.mToast(context, "不能选择超过三十天的日期");
				return;
			}

			// if ( ClickDate - curDate > 100 ) {
			// MyToast.mToast(context, "不能选择超过三十天的日期");
			// return;
			// }

			// if(date.getMonth()!=DateUtil.getMonth()){
			//
			// return;
			// }
			boolean ishave = false;
			for (int i = 0; i < canselectlist.size(); i++) {
				if (date.month == Integer.parseInt((canselectlist.get(i)
						.substring(0, 2)))
						&& date.day == Integer.parseInt((canselectlist.get(i)
								.substring(2, 4)))) {
					ishave = true;
				}
				// if (date.day == canselectlist.get(i)) {
				// ishave = true;
				// }
			}
			// Log.e("lh", ""+mShowDate.getMonth());
			// Log.e("lh", ""+date.getMonth());
			if (ishave) {

				if (mShowDate.getMonth() != date.getMonth()) {
					return;
				}
				// if(!DateUtil.isCurrentMonth(mShowDate)){
				// return;
				// }
			} else {
				MyToast.mToast(context, "您点击选择的日期已被安排，请选择黑色的日期");
				return;
			}

			mCellClickListener.clickDate(date);
			// drawsselect(row,col);
			// 刷新界面
			// update();

			dateSelected(df.format(date.getMonth()) + df.format(date.getDay()));
			// selectetlist.add(df.format(date.getMonth())+df.format(
			// date.getDay()));
			// Log.e("lh", "-----"+date.getMonth()+"---------"+date.getDay());
			fillDate();
//			assignDate(date.getYear(), date.getMonth(), date.getDay());
			// 加
			invalidate();
		}
	}

	/**
	 * 组元素
	 * 
	 * @author wuwenjie
	 * 
	 */
	class Row {
		public int j;

		Row(int j) {
			this.j = j;
		}

		public Cell[] cells = new Cell[TOTAL_COL];

		// 绘制单元格
		public void drawCells(Canvas canvas) {
			for (int i = 0; i < cells.length; i++) {
				if (cells[i] != null) {
					cells[i].drawSelf(canvas);
				}
			}
		}

	}

	/**
	 * 单元格元素
	 * 
	 * @author wuwenjie
	 * 
	 */
	class Cell {
		public CustomDate date;
		public State state;
		public int i;
		public int j;

		public Cell(CustomDate date, State state, int i, int j) {
			super();
			this.date = date;
			this.state = state;
			this.i = i;
			this.j = j;
		}

		public Cell(int i, int j) {
			super();
			this.i = i;
			this.j = j;
		}

		public void drawSelf(Canvas canvas) {
			switch (state) {
			case TODAY: // 今天
				mTextPaint.setColor(Color.parseColor("#ffffff"));
				canvas.drawCircle((float) (mCellSpace * (i + 0.5)),
						(float) ((j + 0.5) * mCellSpace), mCellSpace / 4,
						mCirclePaint);
				break;
			case CURRENT_MONTH_DAY: // 当前月日期
				mTextPaint.setColor(Color.parseColor("#7fd9ff"));
				break;
			case PAST_MONTH_DAY: // 过去一个月
			case NEXT_MONTH_DAY: // 下一个月
				mTextPaint.setColor(Color.parseColor("#7fd9ff"));
				break;
			case UNREACH_DAY: // 还未到的天
				mTextPaint.setColor(Color.parseColor("#7fd9ff"));
				break;
			case PAST_DAY:
				mTextPaint.setColor(Color.parseColor("#7fd9ff"));
				break;
			case CLICK_DAY:
				mTextPaint.setColor(Color.parseColor("#ffffff"));
				canvas.drawCircle((float) (mCellSpace * (i + 0.5)),
						(float) ((j + 0.5) * mCellSpace), mCellSpace / 4,
						mOnclickPaint);
				break;
			case CAN_SELECT:
				mTextPaint.setColor(Color.parseColor("#404040"));
				break;
			case NO_CAN_DAY:
				mTextPaint.setColor(Color.parseColor("#c0c0c0"));
				break;
			default:
				break;
			}

			// 绘制文字
			String content = date.day + "";
			canvas.drawText(content,
					(float) ((i + 0.5) * mCellSpace - mTextPaint
							.measureText(content) / 2), (float) ((j + 0.7)
							* mCellSpace - mTextPaint
							.measureText(content, 0, 1) / 2), mTextPaint);
		}
	}

	/**
	 * 
	 * @author wuwenjie 单元格的状态 当前月日期，过去的月的日期，下个月的日期
	 */
	enum State {
		TODAY, CURRENT_MONTH_DAY, PAST_MONTH_DAY, NEXT_MONTH_DAY, UNREACH_DAY, PAST_DAY, CLICK_DAY, NO_CAN_DAY, CAN_SELECT;
	}

	/** 得到当天的日历 */
	private void initDate() {
		mShowDate = new CustomDate();
		fillDate();//
	}

	/***/
	private void fillDate() {
		int monthDay = DateUtil.getCurrentMonthDay(); // 今天
		int lastMonthDays = DateUtil.getMonthDays(mShowDate.year,
				mShowDate.month - 1); // 上个月的天数
		int currentMonthDays = DateUtil.getMonthDays(mShowDate.year,
				mShowDate.month); // 当前月的天数
		int firstDayWeek = DateUtil.getWeekDayFromDate(mShowDate.year,
				mShowDate.month); // 当月的开始是星期几

		boolean isCurrentMonth = false;
		if (DateUtil.isCurrentMonth(mShowDate)) {
			isCurrentMonth = true;
		}
		int day = 0;
		for (int j = 0; j < TOTAL_ROW; j++) { // 循环得到行数的数组
			rows[j] = new Row(j);
			for (int i = 0; i < TOTAL_COL; i++) { // 循环得到列数的数组
				int position = i + j * TOTAL_COL; // 单元格位置
				// 这个月的
				// 单元格的位置>=当月星期几的开始并且小于星期数加上当月的天数
				if (position >= firstDayWeek
						&& position < firstDayWeek + currentMonthDays) {
					day++;
					rows[j].cells[i] = new Cell(CustomDate.modifiDayForObject(
							mShowDate, day), State.NO_CAN_DAY, i, j);

					// 画可以点击的字体
					for (int s = 0; s < canselectlist.size(); s++) {
						if (mShowDate.getMonth() == Integer
								.parseInt(canselectlist.get(s).substring(0, 2))
								&& day == Integer.parseInt(canselectlist.get(s)
										.substring(2, 4))) {
							rows[j].cells[i] = new Cell(
									CustomDate.modifiDayForObject(mShowDate,
											day), State.CAN_SELECT, i, j);
						}
					}
					

					// 加 是否是当前月 并且 是否小于今天 小于表示是过去的天数
					if (isCurrentMonth && day < monthDay) {
						rows[j].cells[i] = new Cell(
								CustomDate.modifiDayForObject(mShowDate, day),
								State.NO_CAN_DAY, i, j);
					}
					if (isCurrentMonth && day == monthDay) {
						CustomDate date = CustomDate.modifiDayForObject(
								mShowDate, day);
						rows[j].cells[i] = new Cell(date, State.TODAY, i, j);
					}
					
					// 画已经点击了的字体+++++++++
					for (int s = 0; s < selectetlist.size(); s++) {
						if (mShowDate.getMonth() == Integer
								.parseInt(selectetlist.get(s).substring(0, 2))
								&& day == Integer.parseInt(selectetlist.get(s)
										.substring(2, 4))) {
							CustomDate date = CustomDate.modifiDayForObject(
									mShowDate, day);
							rows[j].cells[i] = new Cell(date, State.CLICK_DAY,
									i, j);
						}
					}

					// 过去一个月
				} else if (position < firstDayWeek) {
					rows[j].cells[i] = new Cell(new CustomDate(mShowDate.year,
							mShowDate.month - 1, lastMonthDays
									- (firstDayWeek - position - 1)),
							State.NO_CAN_DAY, i, j);
				}
				// 下个月
				else if (position >= firstDayWeek + currentMonthDays) {
					rows[j].cells[i] = new Cell((new CustomDate(mShowDate.year,
							mShowDate.month + 1, position - firstDayWeek
									- currentMonthDays + 1)), State.NO_CAN_DAY,
							i, j);
				}
			}
		}
		// mCellClickListener.clickDate(mShowDate);
//		mCellClickListener.changeDate(mShowDate);
	}

	public void update() {
		fillDate();
		invalidate();
	}

	// 从左往右划，上一个月
	public void leftSlide() {
		if (mShowDate.month == 1) {
			mShowDate.month = 12;
			mShowDate.year -= 1;
		} else {
			mShowDate.month -= 1;
		}
		update();
	}

	// 从右往左划，下一个月
	public void rightSlide() {
		if (mShowDate.month == 12) {
			mShowDate.month = 1;
			mShowDate.year += 1;
		} else {
			mShowDate.month += 1;
		}
		update();
	}

	public void assignDate(int curyear, int curmonth, int curday) {
		mShowDate = new CustomDate(curyear, curmonth, curday);
		// Log.e("lh", curyear + "." + curmonth + "." + curday);
		int curDay = DateUtil.getCurrentMonthDay();
		/** 点击的天数 */
		int monthDay = curday; /* DateUtil.getCurrentMonthDay(); */// 今天
		int lastMonthDays = DateUtil.getMonthDays(mShowDate.year,
				mShowDate.month - 1); // 上个月的天数
		int currentMonthDays = DateUtil.getMonthDays(mShowDate.year,
				mShowDate.month); // 当前月的天数
		int firstDayWeek = DateUtil.getWeekDayFromDate(mShowDate.year,
				mShowDate.month);
		// Log.e("lh", "firstDayWeek--" + firstDayWeek);
		boolean isCurrentMonth = false;
		if (DateUtil.isCurrentMonth(mShowDate)) {
			isCurrentMonth = true;
		}
		int day = 0;
		for (int j = 0; j < TOTAL_ROW; j++) {
			rows[j] = new Row(j);
			for (int i = 0; i < TOTAL_COL; i++) {
				int position = i + j * TOTAL_COL; // 单元格位置
				// 这个月的
				if (position >= firstDayWeek
						&& position < firstDayWeek + currentMonthDays) {
					day++;
					rows[j].cells[i] = new Cell(CustomDate.modifiDayForObject(
							mShowDate, day), State.NO_CAN_DAY, i, j);

					// 画可以点击的字体
					for (int s = 0; s < canselectlist.size(); s++) {
						if (mShowDate.getMonth() == Integer
								.parseInt(canselectlist.get(s).substring(0, 2))
								&& day == Integer.parseInt(canselectlist.get(s)
										.substring(2, 4))) {
							rows[j].cells[i] = new Cell(
									CustomDate.modifiDayForObject(mShowDate,
											day), State.CAN_SELECT, i, j);
						}
					}
					

					// 加 是否是当前月 并且 是否小于今天 小于表示是过去的天数
					if (isCurrentMonth && day < curDay) {
						rows[j].cells[i] = new Cell(
								CustomDate.modifiDayForObject(mShowDate, day),
								State.NO_CAN_DAY, i, j);
					}
					// 点击的那天
					// if (day == monthDay) {
					// CustomDate date2 = CustomDate.modifiDayForObject(
					// mShowDate, day);
					// rows[j].cells[i] = new Cell(date2, State.CLICK_DAY, i,
					// j);
					//
					// if (isCurrentMonth && day == curDay) {
					// CustomDate date = CustomDate.modifiDayForObject(
					// mShowDate, day);
					// rows[j].cells[i] = new Cell(date, State.TODAY, i, j);
					// }
					// }
					// 今天
					if (isCurrentMonth && day == curDay) {
						CustomDate date = CustomDate.modifiDayForObject(
								mShowDate, day);
						rows[j].cells[i] = new Cell(date, State.TODAY, i, j);
					}
					
					// 画已经点击了的字体+++++++++
					for (int s = 0; s < selectetlist.size(); s++) {
						if (mShowDate.getMonth() == Integer
								.parseInt(selectetlist.get(s).substring(0, 2))
								&& day == Integer.parseInt(selectetlist.get(s)
										.substring(2, 4))) {
							CustomDate date = CustomDate.modifiDayForObject(
									mShowDate, day);
							rows[j].cells[i] = new Cell(date, State.CLICK_DAY,
									i, j);
						}
					}

					// 过去的一个个月
				} else if (position < firstDayWeek) {
					rows[j].cells[i] = new Cell(new CustomDate(mShowDate.year,
							mShowDate.month - 1, lastMonthDays
									- (firstDayWeek - position - 1)),
							State.NO_CAN_DAY, i, j);
					// 下个月
				} else if (position >= firstDayWeek + currentMonthDays) {
					rows[j].cells[i] = new Cell((new CustomDate(mShowDate.year,
							mShowDate.month + 1, position - firstDayWeek
									- currentMonthDays + 1)), State.NO_CAN_DAY,
							i, j);
				}
			}
		}

		invalidate();
		// mCellClickListener.clickDate(mShowDate);
//		mCellClickListener.changeDate(mShowDate);
	}

	// 增加删除选择的日期++++++
	private void dateSelected(String date) {

		boolean isSame = false;
		for (int i = 0; i < selectetlist.size(); i++) {
			if (selectetlist.get(i).equals(date)) {
				selectetlist.remove(i);
				isSame = true;
				continue;
			}

		}
		if (!isSame) {
			selectetlist.add(date);
		}

	}

}
